<template>
  <div class="history-container">
    <el-card class="history-card">
      <template #header>
        <div class="history-header">
          <h2 class="history-title">我的浏览</h2>
          <div class="filter-controls">
            <el-select v-model="selectedCategory" placeholder="选择分类" @change="handleCategoryChange" clearable>
              <el-option label="全部分类" value="" />
              <el-option 
                v-for="category in categories" 
                :key="category.id" 
                :label="category.name" 
                :value="category.id" 
              />
            </el-select>
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
              <el-option label="浏览时间（最新）" value="createTime-desc" />
              <el-option label="浏览时间（最早）" value="createTime-asc" />
              <el-option label="价格（高到低）" value="price-desc" />
              <el-option label="价格（低到高）" value="price-asc" />
            </el-select>
          </div>
        </div>
      </template>
      
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="history.length === 0" class="empty-state">
        <el-empty description="暂无浏览历史" />
      </div>
      
      <div v-else class="history-list">
        <el-card
          v-for="product in history"
          :key="product.id"
          class="history-item"
          @click="handleProductClick(product)"
        >
          <div class="item-content">
            <el-image
              :src="getProductImage(product.coverList)"
              class="product-image"
              fit="cover"
              :preview-src-list="getProductImages(product.coverList)"
            />
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
                             <div class="product-owner">
                 <span class="owner-label">卖家：</span>
                 <span class="owner-name">{{ maskUserName(userInfoMap.get(product.userId)?.userName || userInfoMap.get(product.userId)?.userAccount || '未知用户') }}</span>
               </div>
              <div class="product-price">
                <span class="current-price">¥{{ product.price }}</span>
              </div>
              <div class="product-meta">
                <div class="product-tags">
                  <el-tag v-if="product.isBargain" type="success" size="small">可砍价</el-tag>
                  <el-tag type="info" size="small">{{ getOldLevelText(product.oldLevel) }}</el-tag>
                </div>
                <span class="view-time">浏览于 {{ formatTime(product.createTime) }}</span>
              </div>
            </div>
          </div>
          <div class="item-actions">
            <el-button size="small" @click.stop="handleRemoveHistory(product)">
              删除记录
            </el-button>
          </div>
        </el-card>
      </div>
      
      <div v-if="total > 0" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'
import { getOldLevelText, maskUserName } from '@/utils/product'

const router = useRouter()
const productStore = useProductStore()
const userStore = useUserStore()

const history = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userInfoMap = ref<Map<number, any>>(new Map())

// 分类筛选相关
const categories = ref<any[]>([])
const selectedCategory = ref('')
const sortBy = ref('createTime-desc') // 默认按浏览时间倒序

const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm')
}

const getProductImage = (coverList: string) => {
  try {
    if (!coverList) return '/placeholder.svg'
    
    return coverList  ? coverList : '/placeholder.svg'
  } catch {
    return '/placeholder.svg'
  }
}

const getProductImages = (coverList: string) => {
  try {
    if (!coverList) return ['/placeholder.svg']
    const images = JSON.parse(coverList)
    return images && images.length > 0 ? images : ['/placeholder.svg']
  } catch {
    return ['/placeholder.svg']
  }
}

// 获取用户信息
const fetchUserInfo = async (userId: number) => {
  if (userInfoMap.value.has(userId)) {
    return userInfoMap.value.get(userId)
  }
  
  try {
    const userInfo = await userStore.getUserById(userId)
    if (userInfo) {
      userInfoMap.value.set(userId, userInfo)
    }
    return userInfo
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 加载分类信息
const loadCategories = async () => {
  try {
    // 调用后端分类接口获取分类列表
    const response = await request.get('/category/list', {
      params: {
        pageSize: 20,
      }
    })
    console.log('分类API响应:', response)
    
    // 检查响应数据结构
    if (response && response.data) {
      // 确保response.data是数组
      const categoryData = Array.isArray(response.data) ? response.data : 
                          (response.data.data && Array.isArray(response.data.data)) ? response.data.data : []
      
      if (categoryData.length > 0) {
        categories.value = categoryData.filter((cat: any) => cat.isUse)
      } else {
        throw new Error('分类数据为空')
      }
    } else {
      throw new Error('分类API响应格式错误')
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    // 如果API不可用，使用默认分类
    categories.value = [
      { id: 1, name: '电子产品', isUse: true },
      { id: 2, name: '服装配饰', isUse: true },
      { id: 3, name: '家居用品', isUse: true },
      { id: 4, name: '运动户外', isUse: true },
      { id: 5, name: '图书音像', isUse: true }
    ]
  }
}

// 分类变化处理
const handleCategoryChange = () => {
  currentPage.value = 1 // 分类变化时重置到第一页
  loadHistory()
}

// 排序变化处理
const handleSortChange = () => {
  currentPage.value = 1 // 排序变化时重置到第一页
  loadHistory()
}

const loadHistory = async () => {
  try {
    loading.value = true
    
    // 检查用户是否已登录
    if (!userStore.user || !userStore.user.username) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    const result = await productStore.getUserCollect({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userName: userStore.user.username,
      type: 2, // 浏览历史类型
      categoryId: selectedCategory.value, // 添加分类筛选参数
      sortBy: sortBy.value // 添加排序参数
    })
    
    history.value = result.list
    total.value = result.total
    
    // 为每个商品获取用户信息
    for (const product of history.value) {
      if (product.userId) {
        await fetchUserInfo(product.userId)
      }
    }
  } catch (error: any) {
    console.error('获取浏览历史失败:', error)
    if (error.message && error.message.includes('用户没有足迹')) {
      history.value = []
      total.value = 0
    } else {
      ElMessage.error('获取浏览历史失败')
    }
  } finally {
    loading.value = false
  }
}

const handleProductClick = (product: any) => {
  router.push(`/product/${product.id}`)
}

const handleRemoveHistory = async (product: any) => {
  try {
    // 检查用户是否已登录
    if (!userStore.user || !userStore.user.username) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    await ElMessageBox.confirm(
      '确定要删除这条浏览记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用后端删除浏览记录API
    const deleteParams = {
      userName: userStore.user.username,
      type: 2, // 浏览记录类型
      productId: product.id
    }
    
    console.log('删除浏览记录 - 传递给后端的数据:', deleteParams)
    
    const response = await request.delete('/interaction/delete', {
      params: deleteParams
    })
    
    ElMessage.success('删除成功')
    loadHistory()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadHistory()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadHistory()
}

onMounted(() => {
  loadHistory()
  loadCategories() // 在组件挂载时加载分类信息
})
</script>

<style scoped lang="scss">
.history-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;
}

.history-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  :deep(.el-card__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px 12px 0 0;
  }
}

.history-title {
  text-align: center;
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .el-select {
    min-width: 140px;
  }
}

.loading-state {
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.history-list {
  .history-item {
    margin-bottom: 16px;
    cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
    border-radius: 8px;
    overflow: hidden;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }
  }
}

.item-content {
  display: flex;
  gap: 16px;
  padding: 16px;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  margin: 0 0 8px;
  color: #2c3e50;
  font-weight: 600;
}

.product-owner {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.owner-label {
  color: #999;
}

.owner-name {
  color: #409eff;
  font-weight: 500;
}

.product-price {
  margin-bottom: 12px;
}

.current-price {
  font-size: 20px;
  color: #667eea;
  font-weight: bold;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-tags {
  display: flex;
  gap: 8px;
}

.view-time {
  font-size: 12px;
  color: #7f8c8d;
}

.item-actions {
  display: flex;
  justify-content: flex-end;
  padding: 0 16px 16px;
}

.pagination-wrapper {
  margin-top: 30px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-container {
    padding: 15px;
  }
  
  .history-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .history-title {
    font-size: 20px;
    text-align: center;
  }
  
  .filter-controls {
    justify-content: center;
    flex-wrap: wrap;
    
    .el-select {
      width: 100%;
      max-width: 180px;
    }
  }
  
  .item-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .product-image {
    width: 100%;
    height: 200px;
  }
}
</style> 